#!/bin/bash -eu
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
################################################################################

rm -rf /tmp/chroot
mkdir /tmp/chroot

mkdir /tmp/chroot/lib
mkdir /tmp/chroot/lib64

mkdir /tmp/chroot/usr
mkdir /tmp/chroot/usr/lib

mkdir /tmp/chroot/dev
mknod -m 666 /tmp/chroot/dev/null c 1 3
mknod -m 666 /tmp/chroot/dev/urandom c 1 9

mkdir /tmp/chroot/proc
mkdir /tmp/chroot/tmp

mkdir /tmp/chroot/bin
cp /bin/sh /tmp/chroot/bin/sh
cp $(which llvm-symbolizer) /tmp/chroot/bin/llvm-symbolizer

FULL_EXE_PATH=$(readlink -f $1)
EXE_DIR=$(dirname $FULL_EXE_PATH)
mkdir -p /tmp/chroot/$EXE_DIR

shift

echo 'Running:'
echo minijail0 -U -m \"0 $UID 1\" -T static \
  -c 0 -n -v -p -l -I \
  -k proc,/proc,proc,1 -P /tmp/chroot \
  -b /lib,/lib,0 -b /lib64,/lib64,0 -b /usr/lib,/usr/lib,0 \
  -b /tmp,/tmp,1 \
  -b $EXE_DIR,$EXE_DIR,0 $FULL_EXE_PATH $@

minijail0 -U -m "0 $UID 1" -T static \
  -c 0 -n -v -p -l -I \
  -k proc,/proc,proc,1 -P /tmp/chroot \
  -b /lib,/lib,0 -b /lib64,/lib64,0 -b /usr/lib,/usr/lib,0 \
  -b /tmp,/tmp,1 \
  -b $EXE_DIR,$EXE_DIR,0 $FULL_EXE_PATH $@
